package server;

import org.dom4j.Attribute;
import org.dom4j.Element;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author: wudong
 * @create: 2021-07-26 17:35
 **/
public class Host extends BaseContainer implements Lifecycle,RequestHandler {
    private String appBase;

    @Override
    public void init() throws Exception {
        Element element = getElement();
        Attribute name = element.attribute("name");
        setName(name.getValue());

        Attribute appBase = element.attribute("appBase");
        this.appBase = appBase.getValue();
    }

    @Override
    public void start() throws Exception {
        File dir = new File(appBase);
        if(!dir.isDirectory()){
            throw new RuntimeException(appBase + ",文件夹不存在");
        }

        File[] files = dir.listFiles();
        for (File project : files) {
            if(!project.isDirectory()){
                continue;
            }
            HostConfig hostConfig = new HostConfig(project.getAbsolutePath());
            hostConfig.setParent(this);
            hostConfig.setName(project.getName());

            hostConfig.init();
            hostConfig.start();

            this.addChild(hostConfig);
        }
    }

    @Override
    public void invoke(Request request, Response response) throws Exception {
        HashMap<String, Container> children = this.children;

        String url = request.getUrl();
        String[] split = url.split("/");
        String project = "";
        if(split.length > 1){
            project = split[1];
        }
        HostConfig child = (HostConfig)findChild(project);
        if(child == null){
            response.output(HttpProtocolUtil.getHttpHeader404());
        }else {
            child.invoke(request,response);
        }

    }
}
